package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.UserThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    private final WmMaterialMapper wmMaterialMapper;
    private final WmNewsMaterialService wmNewsMaterialService;
    private final WmNewsAutoScanService wmNewsAutoScanService;
    private final KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 提交审核
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1.校验参数
        //2.自动选择封面
        if (wmNewsDto.getType() == -1) {
            //自动选择封面逻辑
            wmNewsDto = autoSetImages(wmNewsDto);
        }
        //3.封装WmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        wmNews.setStatus(WmNews.Status.SUBMIT.getCode());
        String userId = UserThreadLocal.getUserId();
        wmNews.setUserId(Long.parseLong(userId));
        Date date = new Date();
        wmNews.setCreatedTime(date);
        wmNews.setSubmitedTime(date);
        wmNews.setImages(StringUtils.arrayToCommaDelimitedString(wmNewsDto.getImages()));
        //4.将文章信息存入数据库
        save(wmNews);
        //5.封装图文引用素材信息
        //获取素材id集合(可能为空集合，无图模式)
        String[] images = wmNewsDto.getImages();

        List<WmNewsMaterial> wmNewsMaterials = new ArrayList<>();
        if (!ObjectUtils.isEmpty(images)) {
            LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmMaterial::getUrl, images);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
            List<Long> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            int i = 0;
            for (Long id : ids) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(id);
                wmNewsMaterial.setNewsId(wmNews.getId());
                wmNewsMaterial.setType((short) 1);
                wmNewsMaterial.setOrd(i++);
                wmNewsMaterials.add(wmNewsMaterial);
            }
        }
        wmNewsMaterialService.saveBatch(wmNewsMaterials);
        //文章自动审核 审核成功后自动上架(如果有定时不上架)
        //异步调用
        wmNewsAutoScanService.autoScan(wmNews);
        return ResponseResult.okResult(200, "提交成功!");
    }


    /**
     * 文章内容分页条件查询
     *
     * @param wmNewsPageDto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageDto wmNewsPageDto) {
        //校验参数
        if (wmNewsPageDto.getSize() == null || wmNewsPageDto.getPage() == null || wmNewsPageDto.getPage() < 1
                || wmNewsPageDto.getSize() < 1 || wmNewsPageDto.getSize() > 100) {
            wmNewsPageDto.setPage(1);
            wmNewsPageDto.setSize(10);
        }
        //构造条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(wmNewsPageDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageDto.getChannelId())
                .eq(wmNewsPageDto.getStatus() != null, WmNews::getStatus, wmNewsPageDto.getStatus())
                .between(wmNewsPageDto.getBeginPubDate() != null && wmNewsPageDto.getEndPubDate() != null, WmNews::getPublishTime,
                        wmNewsPageDto.getBeginPubDate(), wmNewsPageDto.getEndPubDate())
                .like(wmNewsPageDto.getKeyword() != null, WmNews::getTitle, wmNewsPageDto.getKeyword())
                .orderByDesc(WmNews::getCreatedTime);
        //封装返回结果
        Page<WmNews> wmNewsPage = new Page<>(wmNewsPageDto.getPage(), wmNewsPageDto.getSize());
        Page<WmNews> page = page(wmNewsPage, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult();
        Long total = page.getTotal();
        pageResponseResult.setTotal(Integer.parseInt(total.toString()));
        Long current = page.getCurrent();
        pageResponseResult.setCurrentPage(Integer.parseInt(current.toString()));
        pageResponseResult.setData(page.getRecords());
        Long size = page.getSize();
        pageResponseResult.setSize(Integer.parseInt(size.toString()));
        return pageResponseResult;
    }

    /**
     * 文章下架
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //获取文章id
        WmNews wmNews= getById(wmNewsDto.getId());
        wmNewsDto.setArticleId(wmNews.getArticleId());
        kafkaTemplate.send("wmNewsDownOrUp-topic",JSONObject.toJSONString(wmNewsDto));
        //上架文章
        update(new LambdaUpdateWrapper<WmNews>().eq(WmNews::getId, wmNewsDto.getId()).set(WmNews::getEnable, wmNewsDto.getEnable()));
        return ResponseResult.okResult(200, "操作成功!");
    }

    /**
     * 自动设置封面信息
     *
     * @param wmNewsDto
     * @return
     */
    private static WmNewsDto autoSetImages(WmNewsDto wmNewsDto) {
        //获取内容图片集合
        String content = wmNewsDto.getContent();
        List<String> imageUrls = new ArrayList<>();
        JSONArray jsonArray = JSON.parseArray(content);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if ("image".equals(jsonObject.getString("type"))) {
                imageUrls.add(jsonObject.getString("value"));
            }
        }
        //内容图片大于等于3 多图
        if (imageUrls.size() >= 3) {
            wmNewsDto.setType((short) 3);
            //从图片集合获取3张
            String[] array = imageUrls.stream().limit(3).toArray(String[]::new);
            wmNewsDto.setImages(array);
        }
        //内容图片大于等于1&&小于3 单图
        if (imageUrls.size() < 3 && imageUrls.size() >= 1) {
            wmNewsDto.setType((short) 1);
            String[] array = imageUrls.stream().limit(1).toArray(String[]::new);
            wmNewsDto.setImages(array);
        }
        //内容没有图片 无图
        if (imageUrls.size() < 1) {
            wmNewsDto.setType((short) 0);
        }
        return wmNewsDto;
    }
}
